<?php

namespace Home\Controller;

class TaskController extends HomeController {
    
	//protected $config = array('app_type' => 'common', 'read' => 'let_me_do,accept,reject,save_log,save_product,delete_product_log,edit_product_log,in_storehouse,folder');

	//过滤查询字段
	function _search_filter(&$map) {
	    
		$map['is_del'] = array('eq', '0');
		if (!empty($_REQUEST['keyword']) && empty($map['64'])) {
			$map['name'] = array('like', "%" . $_POST['keyword'] . "%");
		}
	}
    
	public function index() {
	    
		$this -> redirect('folder', array('fid' => 'no_finish'));
	}

	/*--------------------------------------------------------------------
	 * 任务状态说明
	 * 0 :未处理
	 * 10:进行中
	 * 20:已完成
	 * 21:已转交
	 * 22:已拒绝
	 --------------------------------------------------------------------*/
	public function folder() {
		
		$plugin['date'] = true;
		$this -> assign("plugin", $plugin);
		$this -> assign('auth', $this -> config['auth']);
		$this -> assign('user_id', get_user_id());
		
		$where = $this -> _search();
		if (method_exists($this, '_search_filter')) {
			$this -> _search_filter($where);
		}

		//$no_finish_task_count = badge_count_no_finish_task();
		//$dept_task_count = badge_count_dept_task();
		//$no_assign_task_count = badge_count_no_assign_task();

		//$this -> assign('no_finish_task_count', $no_finish_task_count);
		//$this -> assign('dept_task_count', $dept_task_count);
		//$this -> assign('no_assign_task_count', $no_assign_task_count);

		$fid = $_GET['fid'];
		$this -> assign("fid", $fid);
		$task_list = array();
		switch ($fid) {
			
			case 'all' :
				$this -> assign("folder_name", '所有流程任务');
				break;
				
			case 'dept' :
				$this -> assign("folder_name", '我们部门的任务');
				$auth = $this -> config['auth'];

				if ($auth['admin']) {
					$where_log['type'] = 2;
					$where_log['status'] = array('eq', '0');
					$where_log['executor'] = get_dept_id();
					$task_list = M("TaskLog") -> where($where_log) -> getField('task_id', TRUE);
					if (empty($task_list)) {
						$where['_string'] = '1=2';
					} else {
						$where['id'] = array('in', $task_list);
					}
				} else {
					$where['_string'] = '1=2';
				}
				break;

			case 'no_assign' :
				$this -> assign("folder_name", '不知道由谁处理的任务');

				$prefix = C('DB_PREFIX');

				$assign_list = M("Task") -> getField('id', true);

				$sql = "select id from {$prefix}task task where status=0 and not exists (select * from {$prefix}task_log task_log where task.id=task_log.task_id)";
				$task_list = M() -> query($sql);

				if (empty($task_list)) {
					$where['_string'] = '1=2';
				} else {
					foreach ($task_list as $key => $val) {
						$list[] = $val['id'];
					}
					$where['id'] = array('in', $list);
				}

				break;

			case 'no_finish' :
				$this -> assign("folder_name", '我未完成');

				$where_log['status'] = array('lt', 20);
				$where_log['executor'] = get_user_id();
				$where_log['type'] = array('eq', 1);

				$task_list = M("TaskLog") -> where($where_log) -> getField('task_id', true);
				if (empty($task_list)) {
					$where['_string'] = '1=2';
				} else {
					$where['id'] = array('in', $task_list);
				}

				break;

			case 'finished' :
				$this -> assign("folder_name", '我已完成');

				$where_log['executor'] = get_user_id();
				$where_log['type'] = array('eq', 1);
				$where_log['status'] = array('eq', 20);

				$task_list = M("TaskLog") -> where($where_log) -> getField('task_id', true);
				if (empty($task_list)) {
					$where['_string'] = '1=2';
				} else {
					$where['id'] = array('in', $task_list);
					//$where['status'] = array('in', '20,30');
				}
				break;

			case 'my_task' :
				$this -> assign("folder_name", '我发布的任务');
				$where['user_id'] = get_user_id();
				$task_list = M('task') -> where($where)->getField('id', TRUE);
				break;

			case 'my_assign' :
			    
				$this -> assign("folder_name", '我指派的任务');
				$where_log['assigner'] = get_user_id();
				$task_list = M("TaskLog") -> where($where_log) -> getField('task_id', TRUE);
				if (empty($task_list)) {
					$where['_string'] = '1=2';
				} else {
					$where['id'] = array('in', $task_list);
				}
				break;
			
			case 'my_check' :
				 
				$this -> assign("folder_name", '审核入库');
				$where['check_user_id'] = get_user_id();
				$task_list = M('task') -> where($where)->getField('id', TRUE);
				break;
				
			default :
				break;
		}

		$model = D('Task');
		if (!empty($model)) {
			$this -> _list($model, $where);
		}
		$this->getTaskParent($task_list); 
		$this->assign('li_name',I('post.li_name',''));
		$this->assign('li_content',I('post.li_content',''));
		$this->assign('eq_user_name',I('post.eq_user_name',''));
		$this->assign('be_create_time',I('post.be_create_time',''));
		$this->assign('en_create_time',I('post.en_create_time',''));
		$this -> display();
	}
	
	/**
	 * 获取总任务的名称和总流程数
	 * @param unknown $task_list
	 */
	private function getTaskParent($task_list) {
         
	     $parent_name = array();
	     $process = array();
	     if (!empty($task_list)) {
	         $task = M("task");
	         $where['id'] = array('in', $task_list);
	         $task_pid =  $task -> where($where) -> getField('pid', TRUE);
	         if (!empty($task_pid)) {
	            $task_parent['id'] = array('in', $task_pid);
	            $task_parent_result = M('task_parent')->field('id,task_parent_name,total_process')->where($task_parent)->select();
	            foreach ($task_parent_result as $val) {
	                $parent_name[$val['id']] = $val['task_parent_name'];
	                $process[$val['id']] = $val['total_process'];
	            }
	         }
	     }
	     $this->assign('parent_name',$parent_name);
	     $this->assign('process',$process);
	} 
	
    /**
     * 编辑
     * @see \Home\Controller\HomeController::edit()
     */
	public function edit($id=0) {
	    
	    if (empty($id)) {
	       $this->error('请选择编辑的子任务');           	
	    }
		$plugin['uploader'] = true;
		$plugin['editor'] = true;
		$plugin['date'] = true;
		$this -> assign('plugin', $plugin);
		$model = M('Task');
		
		$vo = $model -> find($id);
		if (empty($vo)) {
		   $this->error('请选择编辑的子任务');
		}
		$task_product = M('task_product') -> where('task_id='.$id) -> field('product,number,product_price,is_check_in,storehouse_product_id') -> select();
		$product = M('storehouse_product')->getField("id,product,product_bh");
		$task_parent = M('task_parent') -> where('id='.$vo['pid']) -> field('id,total_process') -> find();
		
		$this -> assign("task_product", $task_product);
		$this -> assign('product',$product);
		$this -> assign('task_parent',$task_parent);
		$this -> assign('vo', $vo);
		$this -> display();
	}

	public function del($id) {
		$this -> _del($id);
	}

	public function add() {
		
		$plugin['uploader'] = true;
		$plugin['editor'] = true;
		$plugin['date'] = true;
		$this -> assign("plugin", $plugin);
		$product = M('storehouse_product')->getField("id,product,product_bh");
		$this->assign('product',$product);
		$this -> display();
	}
	
	 /**
	  * 插入(non-PHPdoc)
	  * @see \Home\Controller\HomeController::_insert()
	 */
	public function _insert(){
	    
	   $d = $_POST;
	   $model = D('task');
	   if (false === $model -> create()) {
	       $this -> error($model -> getError());
	   }
	   $list = $model -> add();
	   
	   if ($d['is_check_in'] ==0) {  // 不入库的产品
		   	if (!empty($d['product'])) {
		   		$insert = array();
		   		foreach ($d['product'] as $key=>$val) {
		   		    if (empty($val)) {
		   		    	continue;
		   		    }
		   			$insert[$key]['task_id'] = $list;
		   			$insert[$key]['user_id'] = get_user_id();
		   			$insert[$key]['user_name'] = get_user_name();
		   			$insert[$key]['product'] = $val;
		   			$insert[$key]['number'] = $d['number'][$key];
		   			$insert[$key]['product_price'] = empty($d['product_price'][$key]) ? 0 : $d['product_price'][$key];
		   			$insert[$key]['update_at'] = date('Y-m-d H:i:s',time());
		   			$insert[$key]['create_at'] = date('Y-m-d H:i:s',time());
		   		}
		   		$task_product = M('task_product');
		   		$task_product->addAll($insert);
		   	}
		   	
	   } else if($d['is_check_in'] ==1) {  //入库的产品
	   		
	   		$map['id'] = array('in',array_values($d['storehouse_product_id']));

	   		$storeProductResult = M('storehouse_product')->where($map)->field('id,product,product_bh,product_type_id,product_type_name')->select();

	   		$storeProduct = array();
	   	    foreach ($storeProductResult as $val) {
	   	    	$storeProduct[$val['id']] = $val['product'];
	   	    } 

	   	    $insert = array();
	   	    foreach ($d['storehouse_product_id'] as $key=>$val) {
	   	        
	   	        if (empty($storeProduct[$val])) {
	   	        	continue;
	   	        }
	   	    	$insert[$key]['task_id'] = $list;
	   	    	$insert[$key]['user_id'] = get_user_id();
	   	    	$insert[$key]['user_name'] = get_user_name();
	   	    	$insert[$key]['product'] = empty($storeProduct[$val]) ? '' :  $storeProduct[$val];
	   	    	$insert[$key]['number'] = $d['in_number'][$key];
	   	    	$insert[$key]['product_price'] = empty($d['in_product_price'][$key]) ? 0 : $d['in_product_price'][$key];
	   	    	$insert[$key]['is_check_in'] = $d['is_check_in'];
	   	    	$insert[$key]['storehouse_product_id'] = $val;
	   	    	$insert[$key]['update_at'] = date('Y-m-d H:i:s',time());
	   	    	$insert[$key]['create_at'] = date('Y-m-d H:i:s',time());
	   	    }
	   	    $task_product = M('task_product');
	   	    $task_product->addAll($insert);
	   	    
	   }
	   
	   if ($d['is_audit'] ==1) {  // 如果需要人审核
	       $checkArray = explode('|', trim($d['in_check'],';'));
	       $update['check_user_name'] = $checkArray[0];
	       $update['check_user_id'] = $checkArray[1];
	       $update['is_check_in'] = $d['is_check_in'];
	       $update['is_audit'] = $d['is_audit'];
	       $where['id'] = $list;
	       $updateStatus = $model->where($where)->save($update);
	   }
	   
	   if ($list !== false) {
	       $this -> assign('jumpUrl', get_return_url());
	       $this -> success('新增成功!');
	   } else {
	       $this -> error('新增失败!');
	   }
	}
	
	/**
	 * 多流程保存的
	 */
	public function operateSave() {
	    
	    $d = $_POST;
	    $parentId = $this->taskParent($d);
	    if (empty($parentId)) {
	        $this -> error('主任务插入失败');
	    }
	    $taskDmodel = D('task');
	    $taskMmodel = M('task');
	    for ($i = 0;$i<$d['task_num'];$i++) {  // 批量插入任务表
	   		$taskData = array(
	   			'task_no' => $taskDmodel->getTaskNo(),
	   			'pid'	  => $parentId,
	   			'name'	  => empty($d['process_name']) ? '' : $d['process_name'][$i], 
	   			'content' => empty($d['content']) ? '' : $d['content'][$i], 	
	   			'executor'=> empty($d['executor']) ? '' : $d['executor'][$i],
	   			'add_file'=> empty($d['add_file']) ? '' : $d['add_file'],
	   			'expected_time' => empty($d['expected_time']) ? '' : $d['expected_time'][$i], 
	   			'user_id' => get_user_id(),
	   			'user_name' => get_user_name(),
	   			'dept_id' => get_dept_id(),
	   			'dept_name' => get_dept_name(),
	   			'is_check_in' => isset($d['is_check_in']) ? $d['is_check_in'][$i] : 0,
	   			'is_audit' => isset($d['is_audit']) ? $d['is_audit'][$i] : 0,
	   			'status' => 10,
	   		    'is_del' => 0,
	   			'step_process' => $i + 1,
	   			'is_process' => 1, //1代表多流程任务
	   			'create_time' => time(),
	   		);
	   		if (isset($d['is_check_in'][$i]) && $d['is_check_in'][$i] == 1) { // 确定入库的时候
	   			$taskData['into_check_user_name'] =  empty($d['into_check_user_name'][$i]) ? '' : $d['into_check_user_name'][$i];
	   		}
	   		if (isset($d['is_audit'][$i]) && $d['is_audit'][$i] == 1) {
	   			$checkArray = explode('|', trim($d['in_check'][$i],';'));
	   			$taskData['check_user_name'] = $checkArray[0];
	   			$taskData['check_user_id'] = $checkArray[1];
	   		}
	   		$taskId = $taskMmodel->add($taskData);
	   		if($taskId) {
	   			$taskDmodel->sendMessage($taskData['executor']);  // 发送消息
	   		}
	   		$this->taskLog($i,$taskId,$d);
	   		$this->taskProduct($i,$taskId,$d);
	    }
	    $this -> success('发布成功');
	    
	}
	
	/**
	 * 主任务表的插入
	 * @param unknown $param
	 */
	private function taskParent ($param) {
        
	    if (empty($param)) {
	        return false;
	    }
	    if (empty($param['name'])) {
	        $this->error("任务名称不能为空");
	    }
	    if (empty($param['task_type'])) {
	        $this->error("任务类型不能为空");
	    }
	    if (empty($param['task_num'])) {
	        $this->error("任务流程不能为空");
	    }
	    if (!is_numeric($param['task_num'])) {
	    	$this -> error('流程数必须为数字');
	    }
	    if ($param['task_num']<=0 || $param['task_num']>20){
	    	$this -> error('流程数必须大于0和小于等于20');
	    }
	    if (empty($param['task_storehouse_product_id'])) {
	    	$this -> error('请选择发布的产品');
	    }
	    if (empty($param['task_in_number'])) {
	    	$this -> error('请选择发布的产品数');
	    }
	    $result = M('storehouse_product')->where('id='.$param['task_storehouse_product_id'])->field('id,product')->find();
	    if (empty($result)) {
	    	$this -> error('请选择发布的产品');
	    }
	    $data = array(
            'user_id'   => get_user_id(),
	    	'user_name' => get_user_name(),
	        'task_parent_name' => $param['name'],
	        'total_process' => $param['task_num'],
	    	'storehouse_product_id' => $result['id'],
	    	'storehouse_product_name' => $result['product'],
	    	'total_product' => $param['task_in_number'],
	        'is_process'    => $param['task_type'],
	        'update_at'     => date('Y-m-d H:i:s',time()),
	        'create_at'     => date('Y-m-d H:i:s',time())
	    );
	    if (!empty($param['add_file'])) {
	        $data['add_file'] = $param['add_file'];
	    }
	    $task_parent = M('task_parent');
	    $task_parent_id = $task_parent->add($data);
	    return $task_parent_id;
	}
	
	/**
	 * 插入任务日志记录表
	 * @param unknown $i ： key值
	 * @param unknown $taskId ： 任务ID
	 * @param unknown $d ：  表单传过来的参数
	 */
	private function taskLog($i,$taskId,$d) {
        
	    if (empty($d['executor'][$i])) {
	    	return false;
	    }
	    $executor_list = $d['executor'][$i];
	    $executor_list = array_filter(explode(';', $executor_list));
	    $taskLog = M("TaskLog");
	    
	    if (!empty($executor_list)) {
	        foreach ($executor_list as $key => $val) {
	            $tmp = explode('|', $val);
	            $executor_name = $tmp[0];
	            $executor = $tmp[1];
	    
	            if (strpos($executor, "dept_") !== false) {
	                $type = 2;
	                $executor = str_replace('dept_', '', $executor);
	                $where['dept_id']=array('eq',$executor);
	                $dept_user_list=M('User')->where($where)->getField('id',true);
	    
	                foreach($dept_user_list as $val){
	                    $auth=D("Role")->get_auth('Task',$val);
	                    if($auth['admin']){
	                        $user_list[]=$val;
	                    }
	                }
	            } else {
	                $type = 1;
	                $user_list[] = $executor;
	            }
	    
	            $log_data['executor'] = $executor;
	            $log_data['executor_name'] = $executor_name;
	            $log_data['type'] = $type;
	            $log_data['assigner'] = get_user_id();
	            $log_data['task_id'] = $taskId;
	            $taskLog -> add($log_data);
	        }
	        	
	        $push_data['type'] = '任务';
	        $push_data['action'] = '需要执行';
	        $push_data['title'] = "来自：" . get_dept_name()."-".get_user_name();
	        $push_data['content'] = "标题：" . $d['process_name'][$i];
	        $push_data['url'] = U('Task/read',"id={$taskId}&return_url=Task/index");
	        send_push($push_data, $user_list);
	    }	    
	}
	
	/**
	 * 插入任务产品
	 * @param unknown $i
	 * @param unknown $taskId
	 * @param unknown $d
	 */
	private function taskProduct($i,$taskId,$d) {

	    if ($d['is_check_in'][$i] ==0) {    // 不入库的产品
	        if (!empty($d['product'][$i])) {
	            $insert = array();
	            foreach ($d['product'][$i] as $key=>$val) {
	                if (empty($val)) {
	                    continue;
	                }
	                $insert[$key]['task_id'] = $taskId;
	                $insert[$key]['user_id'] = get_user_id();
	                $insert[$key]['user_name'] = get_user_name();
	                $insert[$key]['product'] = $val;
	                $insert[$key]['number'] = $d['number'][$i][$key];
	                $insert[$key]['product_price'] = empty($d['product_price'][$i][$key]) ? 0 : $d['product_price'][$i][$key];
	                $insert[$key]['update_at'] = date('Y-m-d H:i:s',time());
	                $insert[$key]['create_at'] = date('Y-m-d H:i:s',time());
	            }
	            $task_product = M('task_product');
	            $task_product->addAll($insert);
	        }
	    
	    } else if($d['is_check_in'][$i] ==1) {  //入库的产品
	    
	        $map['id'] = array('in',array_values($d['storehouse_product_id'][$i]));
	    
	        $storeProductResult = M('storehouse_product')->where($map)->field('id,product,product_bh,product_type_id,product_type_name')->select();
	    
	        $storeProduct = array();
	        foreach ($storeProductResult as $val) {
	            $storeProduct[$val['id']] = $val['product'];
	        }
	    
	        $insert = array();
	        foreach ($d['storehouse_product_id'][$i] as $key=>$val) {
	             
	            if (empty($storeProduct[$val])) {
	                continue;
	            }
	            $insert[$key]['task_id'] = $taskId;
	            $insert[$key]['user_id'] = get_user_id();
	            $insert[$key]['user_name'] = get_user_name();
	            $insert[$key]['product'] = empty($storeProduct[$val]) ? '' :  $storeProduct[$val];
	            $insert[$key]['number'] = $d['in_number'][$i][$key];
	            $insert[$key]['product_price'] = empty($d['in_product_price'][$i][$key]) ? 0 : $d['in_product_price'][$i][$key];
	            $insert[$key]['is_check_in'] = $d['is_check_in'][$i];
	            $insert[$key]['storehouse_product_id'] = $val;
	            $insert[$key]['update_at'] = date('Y-m-d H:i:s',time());
	            $insert[$key]['create_at'] = date('Y-m-d H:i:s',time());
	        }
	        $task_product = M('task_product');
	        $task_product->addAll($insert);
	    }
	}
	
	
	 /**
	  * 添加每天生产任务产品
	 */
	public function save_product() {
		
		$d = $_POST;
		if (empty($d['task_id'])) {
			$this->output(false,'请选择任务');
		}
		$user_id = get_user_id();
		$dept_id = get_dept_id();
		$task_log = M('task_log');
		$map['task_id'] = $d['task_id'];
		$map['executor'] = array(array('eq',$user_id),array('eq',$dept_id),'or');
		
		$taskLogResult = $task_log->field('id,type,assigner')->where($map)->find();
		if (empty($taskLogResult)) {
			$this->output(false,'该任务你无权提交');
		}
	    $this->dailyTask($d,$taskLogResult); 
		//$this->transferProduct($d,$taskLogResult);
	}
	
	/**
	 * 转交或者入库产品
	 */
	public function transfer_product() {
                    
	    $d = $_POST;
	    if (empty($d['task_id'])) {
	        $this->output(false,'请选择任务');
	    }
	    if (!isset($d['type'])) {
	        $this->output(false,'请选择入库类型');
	    } 
	    $user_id = get_user_id();
	    $dept_id = get_dept_id();
	    $map['task_id'] = $d['task_id'];
	    $map['executor'] = array(array('eq',$user_id),array('eq',$dept_id),'or');
	    $task_log = M('task_log');
	    $taskLogResult = $task_log->field('id,type,assigner')->where($map)->find();
	    if (empty($taskLogResult)) {
	        $this->output(false,'该任务你无权提交');
	    }
	    if ($d['type'] == 0) {
	    	$this->inProduct($d,$taskLogResult);
	    } else if($d['type'] == 1) {
	        $this->transferProduct($d,$taskLogResult);
	    }
	       
	}
	
	/**
	 * 入库产品
	 * @param unknown $d
	 * @param unknown $taskLogResult
	 */
	private function inProduct($d,$taskLogResult) {
        
	    if (count($d['product_id'])<=0) {
	        $this->output(false,'请添加生产产品');
	    }
	    if (count($d['number'])<=0) {
	        $this->output(false,'请添加生产产品数量');
	    }
	    if (count($d['number']) != count($d['product_id'])) {
	        $this->output(false,'产品和数量不一致');
	    }
	    $task_product = M('task_product');
	    $map['id'] = array('in',implode(',',$d['product_id']));
	    $pro = array();
	    $prop = array();
	    $taskProductLog = $task_product->where($map)->field('id,task_id,product,product_price,storehouse_product_id')->select();
	    
	    if (empty($taskProductLog)) {
	        $this->output(false,'任务产品不存在');
	    }
	    
	    foreach ($taskProductLog as $k=>$v) {
	        $pro[$v['id']] = $v['product'];
	        $prop[$v['id']] = $v['product_price'];
	    }
	    
	    $taskRes = M('task') -> where('id='.$d['task_id'])->field('id,pid,user_id,into_check_user_name,is_check_in') -> find();
	    
	    if(empty($taskRes)) {
	        $this->output(false,'任务不存在');
	    }
	    
	    if (!empty($taskRes['into_check_user_name'])) { // 有审核人的时候
	    	
	    	$insert = array();
	    	foreach ($d['product_id'] as $key=>$val) {
	    		 
	    		if (empty($d['number'][$key])) { //如果数量小于零
	    			continue;
	    		}
	    		$insert[$key]['task_product_id'] = $val; // 发布产品的ID
	    		$insert[$key]['dept_id'] = get_dept_id();  //所属部门
	    		$insert[$key]['user_id'] = get_user_id();
	    		$insert[$key]['user_name'] = get_user_name();
	    		$insert[$key]['parent_user_id'] = $taskRes['user_id'];;
	    		$insert[$key]['task_id'] = $d['task_id'];
	    		$insert[$key]['product'] = $pro[$val];
	    		$insert[$key]['number'] = $d['number'][$key];
	    		$insert[$key]['product_price'] = $prop[$val];
	    		$insert[$key]['total_product_price'] = $d['number'][$key]*$prop[$val];
	    		$insert[$key]['into_check_user_name'] = $taskRes['into_check_user_name'];
	    		$insert[$key]['status'] = 0;   // 0未审核|1审核拒绝|2审核通过
	    		$insert[$key]['type'] = 0;     // 0入库|1转交
	    		$insert[$key]['update_at'] = date('Y-m-d H:i:s',time());
	    		$insert[$key]['create_at'] = date('Y-m-d H:i:s',time());
	    	}
	    	$transfer_or_instore_log = M('transfer_or_instore_log');
	    	if (empty($insert)) {
	    		$this->output(false,'请添加产品');
	    	}
	    	$status = $transfer_or_instore_log->addAll($insert);
	    	if ($status) {
	    		$this->output(true,'添加成功');
	    	} else {
	    		$this->output(false,'添加失败,请刷新再试');
	    	}
	    	
	    } else { // 没有审核人的时候
	    	
	    	$storehouse_product = M('storehouse_product');
	    	$storehouse= M('storehouse');
	    	$task_parent = M('task_parent');
	    	$transfer_or_instore_log = M('transfer_or_instore_log');
	    	
	    	foreach ($d['product_id'] as $key=>$val) {
	    		
	    		if (empty($d['number'][$key]) || $d['number'][$key] < 0) { //如果数量小于零
	    			continue;
	    		}
	    		
	    		$insert['task_product_id'] = $val; // 发布产品的ID
	    		$insert['dept_id'] = get_dept_id();  //所属部门
	    		$insert['user_id'] = get_user_id();
	    		$insert['user_name'] = get_user_name();
	    		$insert['parent_user_id'] = $taskRes['user_id'];;
	    		$insert['task_id'] = $d['task_id'];
	    		$insert['product'] = $pro[$val];
	    		$insert['number'] = $d['number'][$key];
	    		$insert['product_price'] = $prop[$val];
	    		$insert['total_product_price'] = $d['number'][$key]*$prop[$val];
	    		$insert['status'] = 2;   // 0未审核|1审核拒绝|2审核通过
	    		$insert['type'] = 0;     // 0入库|1转交
	    		$insert['update_at'] = date('Y-m-d H:i:s',time());
	    		$insert['create_at'] = date('Y-m-d H:i:s',time());
	    		
	    		if (empty($insert)) {
	    			$this->output(false,'请添加产品');
	    		}
	    		
	    		$status = $transfer_or_instore_log->add($insert);
	    		
	    		
	    		$map['id'] = $val;
	    		$taskProductLog = $task_product->where($map)->field('id,task_id,product,product_price,storehouse_product_id')->find();
	    		
	    		$storehouseProductRes = $storehouse_product->field('id,product,product_bh,product_img,product_type_id,product_type_name,convert_unit,convert_number')->where('id='.$taskProductLog['storehouse_product_id'])->find();
	    		if (empty($storehouseProductRes)) {
	    			continue;
	    		}
	    		
	    		$flag = $storehouse_product -> where('id='.$taskProductLog['storehouse_product_id']) -> setInc('num',$d['number'][$key]);
	    		$gg = $storehouse_product -> where('id='.$taskProductLog['storehouse_product_id']) -> setInc('in_num',$d['number'][$key]);
	    		$ee = $task_parent -> where('id='.$taskRes['pid']) -> setInc('finish_product',$d['number'][$key]);
	    	    
	    		$data = array(
    				'product_id'=>$storehouseProductRes['id'],
    				'product_name' => $storehouseProductRes['product'],
    				'product_bh' => $storehouseProductRes['product_bh'],
    				'product_type_id' => $storehouseProductRes['product_type_id'],
    				'product_type_name' => $storehouseProductRes['product_type_name'],
    				'number'  => $d['number'][$key],
    				'type' => 1 ,  // 1入库 | 2出库
    				'user_id' => get_user_id(),
    				'user_name' => get_user_name(),
    				'opreate_name' => get_user_name(),
    				'remark' => '任务流程同意入库操作',
    				'update_at' => date('Y-m-d H:i:s',time()),
    				'create_at' => date('Y-m-d H:i:s',time())
	    		);
	    		$storeId =  $storehouse->add($data);
	    	}
	    	$this->output(true,'添加成功');
	    }
	}
	
	/**
	 * 转交产品
	 * @param unknown $d
	 * @param unknown $taskLogResult
	 */
	private function transferProduct($d,$taskLogResult) {
        
	     if (count($d['transfer_user_id']) <=0) {
	         $this->output(false,'请选择转交人');
	     }
	     if (count($d['transfer_product_id']) <=0) {
	         $this->output(false,'请选择转交产品');
	     }
	     if (count($d['transfer_product_number']) <=0) {
	         $this->output(false,'请选择转交产品数量');
	     }
	     if (count($d['transfer_user_id']) != count($d['transfer_product_id'])) {
	         $this->output(false,'转交人和产品不一致');
	     }
	     
	     $taskRes = M('task') -> where('id='.$d['task_id'])->field('id,pid,user_id,into_check_user_name,is_check_in') -> find();
	      
	     if(empty($taskRes)) {
	     	$this->output(false,'任务不存在');
	     }
	     
	     $task_product = M('task_product');
	     $map['id'] = array('in',implode(',',$d['transfer_product_id']));
	     $pro = array();
	     $prop = array();
	     $taskProductLog = $task_product->where($map)->field('id,task_id,product,product_price,storehouse_product_id')->select();
	     foreach ($taskProductLog as $k=>$v) {
	         $pro[$v['id']] = $v['product'];
	         $prop[$v['id']] = $v['product_price'];
	     }
	     $insert = array();
	     foreach ($d['transfer_product_id'] as $key=>$val) {
	         
	         $explodeUser = explode("|", $d['transfer_user_id'][$key]);
	         if(count($explodeUser) !=  2) {
	             continue;
	         }
	         if (empty($d['transfer_product_number'][$key])) { //如果数量小于零
	             continue;
	         }
	         $insert[$key]['task_product_id'] = $val;   //发布产品的ID
	         $insert[$key]['dept_id'] = get_dept_id();  //所属部门
	         $insert[$key]['user_id'] = get_user_id();
	         $insert[$key]['user_name'] = get_user_name();
	         $insert[$key]['parent_user_id'] = $taskRes['user_id']; // 发布任务人
	         $insert[$key]['task_id'] = $d['task_id'];
	         $insert[$key]['product'] = $pro[$val];
	         $insert[$key]['number'] = $d['transfer_product_number'][$key];
	         $insert[$key]['product_price'] = $prop[$val];
	         $insert[$key]['total_product_price'] = $d['transfer_product_number'][$key]*$prop[$val];
	         $insert[$key]['status'] = 0; //默认审核通过
	         $insert[$key]['type']   = 1; //多流程转交产品
	         $insert[$key]['to_task_id'] = $d['to_task_id'];   // 转交人所属任务id
	         $insert[$key]['to_user_id'] = $explodeUser[1];    // 转交人的uid
	         $insert[$key]['to_user_name'] = $explodeUser[0];  // 转交人的姓名
	         
	         $insert[$key]['update_at'] = date('Y-m-d H:i:s',time());
	         $insert[$key]['create_at'] = date('Y-m-d H:i:s',time());
	         
	         
	         //发送消息
	         $push_data['type'] = '任务';
	         $push_data['action'] = '需要执行';
	         $push_data['title'] = "来自：" . get_dept_name()."-".get_user_name();
	         $push_data['content'] = "标题：转交" . $pro[$val];
	         $push_data['url'] = U('Task/read',"id={$d['task_id']}&return_url=Task/index");
	         send_push($push_data, $explodeUser[1]);
	     }
	     
	     $transfer_or_instore_log = M('transfer_or_instore_log');
	     if (empty($insert)) {
	         $this->output(false,'请添加产品');
	     }
	     $status = $transfer_or_instore_log -> addAll($insert);
	     if ($status) {
	         $this->output(true,'添加成功');
	     } else {
	         $this->output(false,'添加失败,请刷新再试');
	     }
	}
	
	/**
	 * 每天任务
	 * @param unknown $d
	 * @param unknown $taskLogResult
	 */
	private function dailyTask($d,$taskLogResult) {
         
	    if (count($d['product_id'])<=0) {
	        $this->output(false,'请添加生产产品');
	    }
	    if (count($d['number'])<=0) {
	        $this->output(false,'请添加生产产品数量');
	    }
	    if (count($d['number']) != count($d['product_id'])) {
	        $this->output(false,'产品和数量不一致');
	    }
	    $task_product = M('task_product');
	    $map['id'] = array('in',implode(',',$d['product_id']));
	    $pro = array();
	    $prop = array();
	    $taskProductLog = $task_product->where($map)->field('id,task_id,product,product_price')->select();
	    foreach ($taskProductLog as $k=>$v) {
	        $pro[$v['id']] = $v['product'];
	        $prop[$v['id']] = $v['product_price'];
	    }
	    
	    $taskRes = M('task') -> where('id='.$d['task_id'])->field('id,pid,user_id,into_check_user_name,is_check_in') -> find();
	     
	    if(empty($taskRes)) {
	        $this->output(false,'任务不存在');
	    }
	    
	    $insert = array();
	    foreach ($d['product_id'] as $key=>$val) {
	        	
	        if (empty($d['number'][$key])) { //如果数量小于零
	            continue;
	        }
	        $insert[$key]['task_product_id'] = $val; // 发布产品的ID
	        $insert[$key]['dept_id'] = get_dept_id();  //所属部门
	        $insert[$key]['user_id'] = get_user_id();
	        $insert[$key]['user_name'] = get_user_name();
	        $insert[$key]['parent_user_id'] = $taskRes['user_id']; // 发布任务人
	        $insert[$key]['task_id'] = $d['task_id'];
	        $insert[$key]['product'] = $pro[$val];
	        $insert[$key]['number'] = $d['number'][$key];
	        $insert[$key]['product_price'] = $prop[$val];
	        $insert[$key]['total_product_price'] = $d['number'][$key]*$prop[$val];
	        $insert[$key]['status'] = 2; //默认审核通过
	        $insert[$key]['update_at'] = date('Y-m-d H:i:s',time());
	        $insert[$key]['create_at'] = date('Y-m-d H:i:s',time());
	    }
	    $task_product_log = M('task_product_log');
	    if (empty($insert)) {
	        $this->output(false,'请添加产品');
	    }
	    $status = $task_product_log->addAll($insert);
	    
	    if ($status) {
	        $this->output(true,'添加成功');
	    } else {
	        $this->output(false,'添加失败,请刷新再试');
	    }
	}
	
	/**
	 * 更新(non-PHPdoc)
	 * @see \Home\Controller\HomeController::_update()
	 */
	public function _update() {
		
		$d = $_POST;
		if (empty($d['id'])) {
			$this -> error('请选择子任务编辑');
		}
		if ( isset($d['is_check_in']) && $d['is_check_in']==1) {
			if(empty($d['into_check_user_name'])) {
			    $this -> error('请选择入库审核人员');
			}
		}
		$model = D('task');
		$task_product = M('task_product');
		$task_log = M('task_log');
		//强制删除日志产生的冗余数据
		$task_log -> where('task_id='.$d['id']) -> delete();
		
		if (false === $model -> create()) {
			$this -> error($model -> getError());
		}
		$list = $model -> save();
		
		//强制删除日志产生的冗余数据
		$task_product -> where('task_id='.$d['id']) -> delete();
		
		if ($d['is_check_in'] ==0) {  // 不入库的产品 
		    if (!empty($d['product'])) {
		        $insert = array();
		        foreach ($d['product'] as $key=>$val) {
		            $insert[$key]['task_id'] = $d['id'];
		            $insert[$key]['user_id'] = get_user_id();
		            $insert[$key]['user_name'] = get_user_name();
		            $insert[$key]['product'] = $val;
		            $insert[$key]['number'] = $d['number'][$key];
		            $insert[$key]['product_price'] = empty($d['product_price'][$key]) ? 0 : $d['product_price'][$key];
		            $insert[$key]['update_at'] = date('Y-m-d H:i:s',time());
		            $insert[$key]['create_at'] = date('Y-m-d H:i:s',time());
		        }
		        $task_product = M('task_product');
		        $task_product->addAll($insert);
		    }
		    
		   
		    
		} else if ($d['is_check_in'] ==1) {  // 入库的产品

		    $map['id'] = array('in',array_values($d['storehouse_product_id']));
		    
		    $storeProductResult = M('storehouse_product')->where($map)->field('id,product,product_bh,product_type_id,product_type_name')->select();
		    
		    $storeProduct = array();
		    foreach ($storeProductResult as $val) {
		        $storeProduct[$val['id']] = $val['product'];
		    }
		    
		    $insert = array();
		    foreach ($d['storehouse_product_id'] as $key=>$val) {
		        $insert[$key]['task_id'] = $d['id'];
		        $insert[$key]['user_id'] = get_user_id();
		        $insert[$key]['user_name'] = get_user_name();
		        $insert[$key]['product'] = empty($storeProduct[$val]) ? '' :  $storeProduct[$val];
		        $insert[$key]['number'] = $d['in_number'][$key];
		        $insert[$key]['product_price'] = empty($d['in_product_price'][$key]) ? 0 : $d['in_product_price'][$key];
		        $insert[$key]['is_check_in'] = $d['is_check_in'];
		        $insert[$key]['storehouse_product_id'] = $val;
		        $insert[$key]['update_at'] = date('Y-m-d H:i:s',time());
		        $insert[$key]['create_at'] = date('Y-m-d H:i:s',time());
		    }
		    	
		    $task_product = M('task_product');
		    $task_product->addAll($insert);
	        
		}
		
		if ($d['is_audit']==0) {
		    //不审核
		    $update['check_user_name'] = '';
		    $update['check_user_id'] = 0;
		    $update['is_check_in'] = $d['is_check_in'];
		    $update['is_audit'] = 0;
		    $where['id'] = $d['id'];
		    $updateStatus = $model->where($where)->save($update);
		} else if($d['is_audit']==1) {
		    $checkArray = explode('|', trim($d['in_check'],';'));
		    $update['check_user_name'] = $checkArray[0];
		    $update['check_user_id'] = $checkArray[1];
		    $update['is_check_in'] = $d['is_check_in'];
		    $update['is_audit'] = 1;
		    $where['id'] = $d['id'];
		    $updateStatus = $model->where($where)->save($update);
		}
		if ($d['is_check_in']==0) {
		    $up['into_check_user_name'] = '';	
		    $where['id'] = $d['id'];
		    $upStatus = $model->where($where)->save($up);
		}
		
		if (false !== $list) {
			$this -> assign('jumpUrl', get_return_url());
			$this -> success('编辑成功!');
		} else {
			$this -> error('编辑失败!');
		}
	}
	

	public function read($id) {
		
		$plugin['uploader'] = true;
		$plugin['jquery-ui'] = true;
		$plugin['editor'] = true;
		
		$plugin['date'] = true;

		$this -> assign("plugin", $plugin);
		$auth = $this -> config['auth'];
		$this -> assign('auth', $auth);

		$this -> assign('task_id', $id);

		$model = M("Task");
		$vo = $model -> find($id);
		$this -> assign('vo', $vo);

		$where_log['task_id'] = array('eq', $id);
		$task_log = M("TaskLog") -> where($where_log) -> select();
		$this -> assign('task_log', $task_log);
		
		if (empty($vo['executor'])) {
			$this -> assign('no_assign', 1);
		}

		$where_accept['status'] = 0;
		$where_accept['task_id'] = $id;
		$where_accept['type'] = 1;
		$where_accept['executor'] = array('eq', get_user_id());
		$task_accept = M("TaskLog") -> where($where_accept) -> find();

		if ($task_accept) {
			$this -> assign('is_accept', 1);
			$this -> assign('task_log_id', $task_accept['id']);
		}

		if ($this -> config['auth']['admin']) {
			$where_dept_accept['status'] = 0;
			$where_dept_accept['task_id'] = $id;
			$where_dept_accept['type'] = 2;
			$where_dept_accept['executor'] = array('eq', get_dept_id());
			$task_dept_accept = M("TaskLog") -> where($where_dept_accept) -> find();
			if ($task_dept_accept) {
				$this -> assign('is_accept', 1);
				$this -> assign('task_log_id', $task_dept_accept['id']);
			}
		}
		$user_id = get_user_id();
		$where_working['status'] = array('in', '0,10');
		$where_working['task_id'] = $id;
		$where_working['type'] = 1;
		$where_working['executor'] = array('eq', $user_id);
		$task_working = M("TaskLog") -> where($where_working) -> find();

		if (empty($task_working) && $auth['write']) {
			$where_working['type'] = 2;
			$where_working['executor'] = array('eq', get_dept_id());
			$task_working = M("TaskLog") -> where($where_working) -> find();
		}

		if ($task_working) {
			$this -> assign('is_working', 1);
			$this -> assign('task_working', $task_working);
		}
		
		
		$task_product = M('task_product')->where('task_id='.$id)->field('id,task_id,product,number,product_price,is_check_in,storehouse_product_id,create_at')->select();
		
		$task_product_log = M('task_product_log')->field('id,task_product_id,task_id,parent_user_id,user_name,product,number,product_price,total_product_price,status,create_at')->where('task_id='.$id)->limit('0,20')->order('create_at desc')->select();
		
		$transfer_or_instore_log = M('transfer_or_instore_log');
		
		$task_parent = M('task_parent') -> where('id='.$vo['pid']) -> field('task_parent_name,total_process')->find();
		
		$up_transfer_task_product = $transfer_or_instore_log -> where(array('to_task_id'=>$id,'to_user_id'=>$user_id,'type'=>1,'is_del'=>0))->limit('0,20')->order('create_at desc')->select();
		
		$next_transfer_task_product = $transfer_or_instore_log -> where(array('task_id'=>$id,'user_id'=>$user_id,'type'=>1,'is_del'=>0))->limit('0,20')->order('create_at desc')->select();
		
		$my_in_storeHouse = $transfer_or_instore_log -> where(array('task_id'=>$id,'user_id'=>$user_id,'type'=>0,'is_del'=>0)) -> limit('0,20')->order('create_at desc')->select();
		
		$to_my_storeHouse = M('storehouse') -> where(array('to_user_id'=>$user_id,'task_id'=>$id)) -> order('create_at desc')->select();
		
		if (!empty($vo) && !empty($task_parent)) {
            if ( ($vo['step_process']+1) <= $task_parent['total_process'] ) {
                $next_map['pid'] = $vo['pid'];
                $next_map['step_process'] = $vo['step_process'] + 1;
                $next_task_result = M('task')->field('id,executor,step_process')->where($next_map)->find();
                if (!empty($next_task_result)) {
                    $next_task = explode(";", $next_task_result['executor']);
                }
                $next_task_id = $next_task_result['id'];
            }		  	 
		} else {
		    $next_task = array();
		    $next_task_id = 0;
		}
		
		$mapUser['task_id'] = $id;
		$mapUser['user_id'] = get_user_id();
		$userSum = M('task_product_log')->where($mapUser)->sum('total_product_price');
		$numberSum = M('task_product_log')->where($mapUser)->sum('number');
		$this->assign('task_product',$task_product);
		$this->assign('task_product_log',$task_product_log);
		$this->assign('user_id',$user_id);
		$this->assign('userSum',$userSum);
		$this->assign('numberSum',$numberSum);
		$this->assign('task_parent',$task_parent);
		$this->assign('next_task',$next_task);
		$this->assign('next_task_id',$next_task_id);
		$this->assign('up_transfer_task_product',$up_transfer_task_product); // 上流程提交的产品
		$this->assign('next_transfer_task_product',$next_transfer_task_product); // 我提交的下流程产品
		$this->assign('my_in_storeHouse',$my_in_storeHouse);       // 我入库的产品
		$this->assign('my_storeHouse',$to_my_storeHouse);       // 仓库转交我的产品
		$this -> display();
	}
	
	
	//指派人完成的任务产量
	public function load_more_product(){
	    
	    $d = $_POST;
	    if (empty($d['task_id'])) {
	       $this->output(false,'请选择任务');	
	    }
	    if (empty($d['pg'])){
	       $this->output(false,'页数不够');
	    }
	    $p = (((int)($d['pg']-1))*20).', 20';
	    $my_task['task_id'] = $d['task_id'];
	    $task_product_log = M('task_product_log')->where($my_task)->limit($p)->order('create_at desc')->select();
	    if (empty($task_product_log)) {
	        $this->output(false,'加载完毕');
	    } else {
	        $this->output(true,$task_product_log);
	    }
	}
	
	/**
	 * 上流程转交我的产品
	 */
    public function load_transfer_product() {
    	
        $d = $_POST;
        if (empty($d['task_id'])) {
            $this->output(false,'请选择任务');
        }
        if (empty($d['pg'])){
            $this->output(false,'页数不够');
        }
        $p = (((int)($d['pg']-1))*20).', 20';

        $my_task['to_task_id'] = $d['task_id'];
        $my_task['to_user_id'] = get_user_id();
        $my_task['type'] = 1;
        $my_task['is_del'] = 0;
        
        $task_product_log = M('transfer_or_instore_log')->where($my_task)->limit($p)->order('create_at desc')->select();
        if (empty($task_product_log)) {
            $this->output(false,'加载完毕');
        } else {
            $this->output(true,$task_product_log);
        }
    }
    
    // 我转交下流程的产品
    public function load_transfer_next_product() {
		
    	$d = $_POST;
    	if (empty($d['task_id'])) {
    		$this->output(false,'请选择任务');
    	}
    	if (empty($d['pg'])){
    		$this->output(false,'页数不够');
    	}
    	$p = (((int)($d['pg']-1))*20).', 20';
    	
    	$next_task['task_id'] = $d['task_id'];
    	$next_task['user_id'] = get_user_id();
    	$next_task['type'] = 1;
    	$next_task['is_del'] = 0;
    	    	
    	$task_product_log = M('transfer_or_instore_log')->where($next_task)->limit($p)->order('create_at desc')->select();
    	if (empty($task_product_log)) {
    		$this->output(false,'加载完毕');
    	} else {
    		$this->output(true,$task_product_log);
    	}
    }
    
    //我提交入库的产品
    public function load_transfer_in_product() {

    	$d = $_POST;
    	if (empty($d['task_id'])) {
    		$this->output(false,'请选择任务');
    	}
    	if (empty($d['pg'])){
    		$this->output(false,'页数不够');
    	}
    	$p = (((int)($d['pg']-1))*20).', 20';
    	
    	$in_task['task_id'] = $d['task_id'];
    	$in_task['user_id'] = get_user_id();
    	$in_task['type'] = 0;
    	$in_task['is_del'] = 0;
    	$task_product_log = M('transfer_or_instore_log')->where($in_task)->limit($p)->order('create_at desc')->select();
    	if (empty($task_product_log)) {
    		$this->output(false,'加载完毕');
    	} else {
    		$this->output(true,$task_product_log);
    	}
    }
	
	

	function let_me_do($task_id) {
	    
		if (IS_POST) {
			M("Task") -> where("id=$task_id") -> setField('executor', get_user_name() . "|" . get_user_id());
			M("Task") -> where("id=$task_id") -> setField('status', 10);

			$data['task_id'] = I('task_id');
			$data['executor'] = get_user_id();
			$data['executor_name'] = get_user_name();
			$data['transactor'] = get_user_id();
			$data['transactor_name'] = get_user_name();
			$data['status'] = 10;
			$data['type'] = 1;
						
			$task_id = I(task_id);
			$list = M("TaskLog") -> add($data);
			if ($list != false) {
				//$this -> _add_to_schedule($task_id);
				$return['info'] = '接受成功';
				$return['status'] = 1;
				$this -> ajaxReturn($return);
			} else {
				$this -> error('提交成功');
			}
		}
	}

	/**
	 * 保存日志
	 * @param unknown $id
	 */
	public function save_log($id) {
		
	    $model = D("TaskLog");
		if (false === $model -> create()) {
			$this -> error($model -> getError());
		}
		
		$model -> transactor = get_user_id();
		$model -> transactor_name = get_user_name();

		$status = I('status');
		$finish_rate = I('finish_rate');
		$task_log_id = $id;

		if ($finish_rate == '100.00') {
			$model -> finish_time = to_date(time());
			$model -> status = 20;
			$status = 20;
		}
		
		if($model -> status==22) {
			$model -> finish_time = to_date(time());
		}

		$list = $model -> save();

		$task_id = M("TaskLog") -> where("id=$task_log_id") -> getField('task_id');

		if ($status == 10) {
			M("Task") -> where("id=$task_id") -> setField('status', 10);
		}

		if ($status >= 20) {
			
		    $where_total_count['task_id'] = array('eq', $task_id);
			$total_count = M("TaskLog") -> where($where_total_count) -> count();

			$where_finish_count['task_id'] = array('eq', $task_id);
			$where_finish_count['status'] = array('egt', 20);
			$finish_count = M("TaskLog") -> where($where_finish_count) -> count();

			if ($total_count == $finish_count) {
			    
				M("Task") -> where("id=$task_id") -> setField('status', 30);

				$user_id = M('Task') -> where("id=$task_id") -> getField('user_id');
            
				$task = M("Task") -> where("id=$task_id") -> find();
            
				$transactor_name = get_user_name();

				$push_data['type'] = '任务';
				$push_data['action'] = '已完成';
				$push_data['title'] = "{$transactor_name}已完成您发起的[{$task['name']}]任务";
				$push_data['content'] = "如有问题，请与[{$transactor_name}]进行沟通。";
				$push_data['url'] = U('Task/read',"id={$task['id']}&return_url&Task/index");

				send_push($push_data, $user_id);
			}
		}

		if ($status == 21) {
			$task_id = I('task_id');
			$forword_executor = I('forword_executor');
			D('Task') -> forword($task_id, $forword_executor);
		}
		if ($status == 22) {

		}
		if ($list !== false) {
			$this -> assign('jumpUrl', get_return_url());
			$this -> success('提交成功!');
		} else {
			$this -> error('提交失败!');
		}
	}

	function upload() {
		$this -> _upload();
	}

	function down($attach_id) {
		$this -> _down($attach_id);
	}

	private function _add_to_schedule($task_id) {
		$info = M("Task") -> where("id=$task_id") -> find();
		$data['name'] = $info['name'];
		$data['content'] = $info['content'];
		$data['start_time'] = to_date(time());
		$data['end_time'] = $info['expected_time'];
		$data['user_id'] = get_user_id();
		$data['user_name'] = get_user_name();
		$data['priority'] = 3;

		$list = M('Schedule') -> add($data);
	}

	function _send_mail_finish($task_id, $executor) {
		
		$executor_info = M("User") -> where("id=$executor") -> find();
		
		$email = $executor_info['email'];
		$user_name = $executor_info['name'];
		
		$info = M("Task") -> where("id=$task_id") -> find();
		
		$transactor_name = M("TaskLog") -> where("task_id=$task_id") -> getField('id,transactor_name');

		$transactor_name = implode(",", $transactor_name);

		$title = "您发布任务已完成：" . $info['name'];

		$body = "您好，{$user_name}，{$transactor_name} 完成了您发起的[{$info['name']}]任务</br>";
		$body .= "任务主题：{$info['name']}</br>";
		$body .= "任务时间：{$info['expected_time']}</br>";
		$body .= "任务执行人：{$transactor_name}</br>";
		$body .= "请及时检查任务执行情况，如有问题，请与[{$transactor_name}]进行沟通。</br>";
		$body .= "任务完成后请对[任务执行人]表达我们的感谢。</br>";

		$body .= "点击查看任务详情：http://" . $_SERVER['SERVER_NAME'] . U('Task/read', 'id=' . $info['id']) . "</br>";
		$body .= "霞湖世家，感谢有您！</br>";
		//send_mail($email, $user_name, $title, $body);
	}
	
	/**
	 * 删除提交产品任务记录
	 */
	function delete_product_log() {
	    
	   $d = $_POST;
	   if (empty($d['log_id'])) {
	   	   $this->output(false,'请选择删除记录');
	   } 
	   $taskProductLog = M('task_product_log'); 
	   $map['id'] = $d['log_id'];
	   $status = $taskProductLog->where($map)->delete();
	   if ($status) {
	       $this->output(true);
	   } else {
	       $this->output(false,'请刷新重试');
	   }
	}
	
	/**
	 * 编辑产品的提交数量
	*/
	function edit_product_log() {
        
	    $d = $_POST;
	    if (empty($d['log_id'])) {
	        $this->output(false,'请选择删除记录');
	    }
	    if (empty($d['number'])) {
	        $this->output(false,'请选择产品数量');
	    }
	    $map['id'] = $d['log_id'];
	    $task = M('task_product_log');
	    $taskProductLog = $task -> where($map) -> field('id,product,number,product_price') -> find();
	    if (empty($taskProductLog)) {
	        $this->output(false,'请选择有效记录');
	    }
	    
	    $data['number'] = $d['number'];
	    $data['total_product_price'] = $d['number']*$taskProductLog['product_price'];
	    $status = $task -> where($map) -> save($data);
	    if ($status) {
	        $this->output(true,'修改成功');
	    } else {
	        $this->output(false,'修改失败，请刷新页面重新再试');
	    }
	}
	
	/**
	 * 入库操作
	 */
	function in_storehouse() {
        
	    $d = $_POST;
	    if (empty($d['log_id'])) {
	        $this->output(false,'请选择删除记录');
	    }
	    $map['id'] = $d['log_id'];
	    $task = M('task_product_log');
	    $product = M('task_product');
	    $storehouse_product = M('storehouse_product');
	    $storehouse = M('storehouse');
	    $taskProductLog = $task -> where($map) -> field('id,task_product_id,number') -> find();
	    if (empty($taskProductLog)) {
	        $this->output(false,'请选择有效记录');
	    }
	    $productMap['id'] = $taskProductLog['task_product_id'];
	    $productLog = $product->where($productMap)->field('id,task_id,is_check_in,storehouse_product_id')-> find();
	    if (empty($productLog)) {
	        $this->output(false,'请选择有效产品');
	    }
	    if ($productLog['is_check_in'] ==0) {
	        $this->output(false,'该产品不需要入库');
	    }
	    
	    $storeHouseProductMap['id'] = $productLog['storehouse_product_id'];
	    $storehouse_product_result = $storehouse_product->where($storeHouseProductMap)->field('id,product,product_bh,product_type_id,product_type_name')-> find();
	    if (empty($storehouse_product_result)) {
	        $this->output(false,'请选择有效产品');
	    }
	    
	    $insert = array(
            'product_id'=>$storehouse_product_result['id'],
            'product_name' => $storehouse_product_result['product'],
            'product_bh' => $storehouse_product_result['product_bh'],
            'product_type_id' => $storehouse_product_result['product_type_id'],
            'product_type_name' => $storehouse_product_result['product_type_name'],
            'number'  => $taskProductLog['number'],
            'type' => 1,
            'user_id' => get_user_id(),
            'user_name' => get_user_name(),
            'opreate_name' => get_user_name(),
            'remark' => '生产任务入库',
            'update_at' => date('Y-m-d H:i:s',time()),
            'create_at' => date('Y-m-d H:i:s',time())
	    );
	    
	    $data['is_in'] = 1;
	    
	    $task->startTrans();
	    $status = $task -> where($map) -> save($data);
	    $flag = $storehouse_product -> where($storeHouseProductMap) -> setInc('num',$taskProductLog['number']);
	    $gg = $storehouse_product -> where($storeHouseProductMap) -> setInc('in_num',$taskProductLog['number']);
	    $hh = $storehouse -> add($insert);
	    if ($status && $flag && $gg && $hh) {
	        $task->commit();
	        $this->output(true,'入库成功');
	    } else {
	        $task->rollback();
	        $this->output(false,'入库失败');
	    }
	    
	}
	
	/**
	 * 接受或者拒绝上流程转交我的产品
	 */
	function do_transfer_product() {
            
	    $d = $_POST;
	    if (empty($d['log_id'])) {
	        $this->output(false,'请选择删除记录');
	    }
	    if (empty($d['status'])) {
	    	$this->output(false,'请选择操作类型');
	    }
	    if (!in_array($d['status'],array(1,2))) {
	    	$this->output(false,'请选择操作类型');
	    }
	    $map['id'] = $d['log_id'];
	    if ( $d['status']==2 ) {
	    	$data['status'] = 2;
	    } else {
	    	$data['status'] = 1;
	    }
	    $status = M('transfer_or_instore_log')->where($map)->save($data);
	    if ($status) {
	        $this->output(true,'接受成功');
	    } else {
	        $this->output(false,'接受失败');
	    }
	}
	
	/**
	 * 删除我转交下流程的产品
	 */
	function del_next_transfer_product() {
		
		$d = $_POST;
		if (empty($d['log_id'])) {
			$this->output(false,'请选择删除记录');
		}
		$map['id'] = $d['log_id'];
		$map['user_id'] = get_user_id();
		$map['type'] = 1; //0入库|1转交
		$data['is_del'] = 1;
		$status = M('transfer_or_instore_log')->where($map)->save($data);
		if ($status) {
			$this->output(true,'成功');
		} else {
			$this->output(false,'失败');
		}
	}
	
	//删除我提交入库的产品
	function del_in_transfer_product() {
		
		$d = $_POST;
		if (empty($d['log_id'])) {
			$this->output(false,'请选择删除记录');
		}
		$map['id'] = $d['log_id'];
		$map['user_id'] = get_user_id();
		$map['type'] = 0;  //0入库|1转交
		$data['is_del'] = 1;
		$status = M('transfer_or_instore_log')->where($map)->save($data);
		if ($status) {
			$this->output(true,'成功');
		} else {
			$this->output(false,'失败');
		}
		
	}
	
	
	/**
	 * 统计任务的
	 * 所有的任务
	*/
	public function statis() {

		$plugin['date'] = true;
		$ty = $_GET['ty'];
	    $map = array();
	    if (!empty($_REQUEST['name'])) {
	        $map['task_parent_name'] = array('like', '%' . trim($_REQUEST['name']) . '%');
	    }
	    if (!empty($_REQUEST['user_name'])) {
	    	$map['user_name'] = array('like', '%' . trim($_REQUEST['user_name']) . '%');
	    }
	    if (!empty($_REQUEST['be_create_time'])) {
	    	$map['create_at'] = array('EGT', trim($_REQUEST['be_create_time']));
	    }
	    if (!empty($_REQUEST['en_create_time'])) {
	    	$map['create_at'] = array('ELT', trim($_REQUEST['en_create_time']));
	    }
	    $map['is_del'] = array('eq',0);
	    $name = empty($_REQUEST['name']) ? '' : $_REQUEST['name'];
	    $user_name = empty($_REQUEST['user_name']) ? '' : $_REQUEST['user_name'];
	    $be_create_time = empty($_REQUEST['be_create_time']) ? '' : $_REQUEST['be_create_time'];
	    $en_create_time = empty($_REQUEST['en_create_time']) ? '' : $_REQUEST['en_create_time'];
	    
	    if(empty($ty)) {
	    	$no_finish_task_count = badge_count_no_finish_task();
	    	$dept_task_count = badge_count_dept_task();
	    	
	    	$this -> assign('no_finish_task_count', $no_finish_task_count);
	    	$this -> assign('dept_task_count', $dept_task_count);
	    }
	    
	    $model = M('task_parent');
	    $this -> _list($model, $map);
	    $this -> assign('user_id',get_user_id());
	    $this -> assign("ty", $ty);
	    $this -> assign('name',$name);
	    $this -> assign("user_name",$user_name);
	    $this -> assign("be_create_time",$be_create_time);
	    $this -> assign("en_create_time",$en_create_time);
	    $this -> assign("plugin", $plugin);
	    $this->display();
	}
	
	/**
	 * 查看所有子任务
	*/
	public function see($pid=0) {
		
		if (empty($pid)) {
			$this->error('请选择主任务');
		}
		$user_id = get_user_id();
		$map['pid'] = $pid;
		$map['is_del'] = 0; // 未删除
		$childTask = M('task') -> where($map) -> order('create_time desc')-> select();
		$parentTask = M('task_parent') -> where('id='.$pid) -> field('id,total_process') -> find();
		$this->assign('list',$childTask);
		$this->assign('user_id',$user_id);
		$this->assign('task_parent',$parentTask);
		$this->display();
	}
	
	/**
	 * 删除总任务
	*/
	public function delTaskParent($id=0) {
        
        if (empty($id)) {
            $this->error('请选择任务');
        } 
        $taskParent = M('task_parent');
        $task = M('task');
        $data['is_del'] = 1;
        $taskParentMap['id'] = $id;
        $taskMap['pid'] = $id;
        $taskParent->startTrans();
        $status = $taskParent->where($taskParentMap)->save($data);
        $state = $task->where($taskMap)->save($data);
        if ($status && $state) {
            $taskParent->commit();
            $this -> success('删除成功');
        } else {
            $taskParent->rollback();
            $this -> error('删除失败');
        }
	}
	
	/**
	 * 接受仓库发过来的产品
	 */
	public function receive_storeHouse_product() {
		
		$d = $_POST;
		if (empty($d['log_id'])) {
			$this->output(false,'请选择记录');
		}
		if (empty($d['type']) || !in_array($d['type'], array(1,2)) ) {
			$this->output(false,'请选择操作类型');
		}
		$storehouse = M('storehouse');
		$map['id'] = $d['log_id'];
		$result = $storehouse -> where($map) ->field('id,product_id,number') -> find();
		if (empty($result)) {
			$this->output(false,'请选择记录');
		}
		$status = false;
		if ($d['type'] ==1) {         //接受
			
			$data['status'] = 1;    // 成功
			$storehouse_product = M('storehouse_product');
			$storehouse->startTrans();
			$status = $storehouse->where($map)->save($data);
			$flag = $storehouse_product -> where('id='.$result['product_id']) -> setDec('num',$result['number']);
			$gg = $storehouse_product -> where('id='.$result['product_id']) -> setInc('out_num',$result['number']);
			if ($status && $flag && $gg) {
				$storehouse->commit();
				$status = true;
			} else {
				$storehouse->rollback();
				$status = false;
			}
			
		} else if ($d['type'] ==2) {  // 拒绝的时候
			$map['id'] = $d['log_id'];
			$data['status'] = 3;  // 拒绝
			$status = $storehouse->where($map)->save($data);
		}
		if ($status) {
			$this->output(true,'操作成功');
		} else {
			$this->output(false,'操作失败');
		}
	}
}
